<template>
    <a-spin :loading="pageData.pageLoading" style="width: 100%;">
        <div class="bg-container">

            <Toolbar :items="['查询', '新增', '删除', '导出', '导入']" @add="addHandler" @import="importHandler"
                @del="deleteHandler" @select="selectHandler" @export="exports" @excel="downloadHandler">
            </Toolbar>
        </div>

        <div class="gang"></div>

        <div style="padding: 10px; box-sizing: border-box">
            <a-tabs   :lazy-load="true">
                <a-tab-pane title="物料分类">
                    <!-- <a-table style="height:100%"
                        size="mini" :scrollbar="true" sticky-header
                        @page-change="pagination.change" stripe :bordered="true" :columns="tableColumns"
                        :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                        v-model:selected-keys="selectedRowKeys" :loading="table.tableLoading" :data="table.dataList"
                        :pagination="{ size: 'small', current: pagination.page, pageSize: pagination.pageSize, total: pagination.total, showPageSize: false, pageSizeOptions: [10, 20, 30, 50, 100] }"
                        :rowKey="rowKey">
                   <template #deleteState="{ record }">-->
<!--                            <a-button v-if="record.deleteState == 1" type="primary" size="small" status="warning" disabled>已删除-->
<!--                            </a-button>-->
<!--                        </template>-->
                        <!-- <template #action="{ record }">
                            <a-button v-if="record.deleteState == 0" type="primary" size="small" status="warning" @click="editHandler(record)">
                                <template #icon>
                                    <icon-edit />
                                </template>
                                修 改
                            </a-button>
                        </template>
                    </a-table> -->
                      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%" :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc"></AgGridVuesCopys>
                </a-tab-pane>
            </a-tabs>
        </div>
    </a-spin>
    <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd"
        unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false"  >
        <template #title>
            {{ pageData.sideTitle }}
        </template>
        <div>
            <a-form ref="formRef" layout="vertical" :model="dataForm">
                <a-form-item label="编号" field="classCode"
                    :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
                    :validate-trigger="['change', 'blur']">
                    <a-input placeholder="" v-model="dataForm.classCode" @blur="inputBlur" />
                </a-form-item>
                <a-form-item label="分类名称" field="className" :validate-trigger="['change', 'blur']"
                    :rules="[{ required: true, message: '分类名称必填' }]">
                    <a-input placeholder="" v-model="dataForm.className" />
                </a-form-item>
                <a-form-item label="默认仓库">
                    <a-select popup-container="html"  :style="{ width: '100%' }" :loading="loading"
                        @search="handleSearch" :filter-option="false" allow-search
                        v-model.trim="dataForm.warehouseName" @click="handleSearchs" allow-clear>
                        <a-option v-for="item in pageData.warehouseName" :key="item" :value="item.warehouseName">{{
                                item.warehouseName
                        }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="备注" field="remark">
                    <a-input  v-model="dataForm.remark" />
                </a-form-item>
            </a-form>
        </div>
    </a-drawer>
</template>

<script lang="ts">
import { post } from "@/api/http";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";

import { ref, reactive, onMounted, onActivated } from "vue";
import Toolbar from "@/components/Toolbar.vue";
import { Form, Message, Modal } from "@arco-design/web-vue";
import { FormInstance } from "@arco-design/web-vue/es/form";
import emitter from "@/hooks/useEventBus";
import validate from "@/hooks/useValidate";
import { DatasetComponent } from "echarts/components";
import { AnyARecord } from "dns";
import { baseURL } from '../../../api/axios.config'
import axios from "axios";

interface ClothInfo {
    id: number | string | null;
    classCode: string;
    className: string;
    warehouseName: string;
    remark: string;
    deleteState: string | undefined | null;
    createName: string | undefined | null;
    createTime: string | undefined | null;
    updateName: string | undefined | null;
    updateTime: string | undefined | null;
}
export default {
    name: "MaterialClassification",
    setup() {
        //查询
        function doRefresh() {
            pageData.pageLoading = true
            post({
                url: "product/MaterialClass/getPage",
                data: {
                    page: pagination.page,
                    size: pagination.pageSize
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {

                        table.handleSuccess(data.list);
                        pagination.setTotalSize(data.total);
                                  // 查询方法改

                         gridOption.value.setRowData(data.list)

                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }
        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([
            {
                title: "编号",
                key: "classCode",
                dataIndex: "classCode",
                width: 150
            },
            {
                title: "分类名称",
                key: "className",
                dataIndex: "className",
                width: 150
            },
            {
                title: "默认仓库",
                key: "warehouseName",
                dataIndex: "warehouseName",
                width: 150
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 150
            },
            {
                title: "最后修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150
            },
            {
                title: "最后修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 150
            },
            // {
            //     title: "删除状态",
            //     key: "deleteState",
            //     dataIndex: "deleteState",
            //     width: 100,
            //     slotName: "deleteState",
            //     fixed: 'right'
            // },
            {
                title: "操作",
                key: "id",
                dataIndex: "id",
                slotName: "action",
                width: 150, fixed: 'right'
            },
        ]);
        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            pageLoading: boolean,
            rHeight: any,
            warehouseName:any,
            remark: string,
        }>({
            showAdd: false,
            sideTitle: "新增物料分类",
            dropDownData: "",
            pageLoading: false,
            rHeight: "",
            warehouseName:[],
            remark: "",
        });

        // 表格准备事件
        const gridOption = ref()
         const gridReady = (params:any) =>{
            gridOption.value = params.api
         }
        onMounted(() => {
            pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight
            //表格的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight - 200;
                console.log(pageData.rHeight);

            }
            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight

                //表格的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight - 200;
                }

            })
        });
        //查询
        const selectHandler = () => {
            doRefresh();
        }
        const addHandler = () => {
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                } else {
                    dataForm[key] = "";
                }

            }
            pageData.showAdd = true;
            pageData.sideTitle = "新增物料分类";
        };
        const dataForm = reactive<ClothInfo>({
            id: null,
            classCode: "",
            className: "",
            warehouseName: "",
            remark: "",
            deleteState: "",
            createName: "",
            createTime: "",
            updateName: "",
            updateTime: "",
        });
        const formRef = ref<FormInstance>();
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    if (pageData.sideTitle === "新增物料分类") {
                        post({
                            url: "product/MaterialClass/insert",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();

                                pageData.showAdd = false;

                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }

                        });
                    } else {
                        post({
                            url: "product/MaterialClass/update",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;

                                Message.success({
                                    content: "修改成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }

                        });
                    }
                }
            });
        };
        const deleteHandler = () => {
            
            if (gridOption.value.getSelectedRows().length === 0) {
                return
            }
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                onOk() {
                    post({
                        url: "product/MaterialClass/deleteList",
                        data:  gridOption.value.getSelectedRows().map((o:any)=>{return o.id})
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });
                            pagination.page = 1
                            doRefresh()
                        } else {
                            Message.error({
                                content: "修改失败",
                                duration: 5000,
                            });
                        }

                    });
                },
            });
        };
        const editHandler = (record: ClothInfo) => {
            dataForm.id = record.id;
            dataForm.classCode = record.classCode;
            dataForm.className = record.className;
            dataForm.warehouseName = record.warehouseName;
            dataForm.remark = record.remark;
            pageData.sideTitle = '修改物料分类'
            pageData.showAdd = true
        };
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })

        }
        //input离开焦点 将小写转大写
        const inputBlur = () => {
            dataForm.classCode = dataForm.classCode.toUpperCase();
        }
        //导出
        const exports = () => {
            if (selectedRowKeys.value.length === 0) {
                Message.error('请先勾选')
                return
            } else {
                //将表头拼接出来
                let head = "<th>编号</th><th>分类名称</th><th>默认仓库</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return selectedRowKeys.value.indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["classCode"] + "</td>";
                    body += "<td>" + o["className"] + "</td>";
                    body += "<td>" + o["warehouseName"] + "</td>";
                    body += "<td>" + o["remark"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '物料分类', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }

        // const importHandler = () => {
        //     const inputEle: HTMLInputElement = document.createElement('input')
        //     inputEle.type = 'file'
        //     inputEle.id = 'fileUploadExcel'
        //     inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        //     inputEle.addEventListener('change', () => {
        //         console.log(this)
        //     })
        // }
        //       //模板下载
        const downloadHandler = () => {
            window.open(baseURL + 'excel')
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/product/MaterialClass/importModelData', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        const options = ref<any>(pageData.warehouseName);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { warehouseName: value }
                loading.value = true;
                window.setTimeout(() => {
                    selCxAll(ob);
                    options.value = pageData.warehouseName;
                    loading.value = false;
                }, 100)
            } else {
                options.value = []
            }
        };
        function selCxAll(val: any) {
            post({
                url: "wms/warehouse/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data)
                    pageData.warehouseName = data;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        const handleSearchs = () => {
            post({
                url: "wms/warehouse/getFieldValue",
                data: {
                    warehouseName: ''
                }
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data)
                    pageData.warehouseName = data;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        let tc:any[] = tableColumns.map((o:any)=>{

let obj = {
    headerName:o.title,
    field:o.key,
    pinned:o['fixed']
}
if(o.slotName === 'action'){
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj["lockPosition"]="right"

    obj['cellRenderer'] = {
        template:`<a-tag class="tagCss" @click="a">修改</a-tag>`,
        setup(props:any){
            const a = () =>{
                editHandler(props.params.data)
            }
            return {
                a
            }
        }
        
    }
}

return obj
})

let a = [{
showRowGroup: 'hide_def',
"headerName": "",
"checkboxSelection": true,
"headerCheckboxSelection": true,
"pinned": "left",
"width": 50,
resizable: false,
filter:false,
sortable:false,
minWidth: 50,
maxWidth: 50,
lockPosition:"left",
}]
tc = a.concat(tc)
        const defaultColDef = {
            sortable: true,
            resizable:true,
            filter: true,
            //flex: 1
          }
        return {
            defaultColDef,
            tc,
            handleSearchs,
            handleSearch,
            loading,
            importHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            editHandler,
            selectHandler,
            inputBlur,
            isChiese,
            exports,
            downloadHandler,
            gridReady
        };
    },
    components: { Toolbar,  },
};
</script>
<style scoped lang="less">

</style>
